package com.ishare.common.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 李嘉宾
 * @since 1.0.0
 */
public class MyBeanUtils {

    /**
     * 将来源对象的不为空的属性赋值到目标对象中
     *
     * @param source 来源对象
     * @param target 目标对象
     * @throws IllegalAccessException
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) throws IllegalAccessException {
        //获取源对象的所有属性的值
        Class<?> aClass = source.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        Field[] declaredFieldsSuper = aClass.getSuperclass().getDeclaredFields();
        List<String> ignoreNames = new ArrayList<>();
        getIgnore(source, declaredFields, ignoreNames);
        getIgnore(source, declaredFieldsSuper, ignoreNames);
        String[] ignoreNamesArr = new String[ignoreNames.size()];
        BeanUtils.copyProperties(source, target, ignoreNames.toArray(ignoreNamesArr));
    }

    private static void getIgnore(Object source, Field[] declaredFieldsSuper, List<String> ignoreNames) throws IllegalAccessException {
        for (Field field : declaredFieldsSuper) {
            field.setAccessible(true);
            if (field.get(source) == null || StringUtils.isEmpty(field.get(source))) {
                ignoreNames.add(field.getName());
            }
        }
    }

}
